package com.ihr360.payroll.model.dto.salary.plan.config;

import com.ihr360.commons.lang.CollectionUtils;
import com.ihr360.commons.model.meta.table.DynamicHeaderCell;
import com.ihr360.payroll.model.dto.salary.meta.PayrollConfig;
import com.ihr360.payroll.model.dto.salary.meta.SalaryField;
import com.ihr360.payroll.model.dto.salary.plan.payslip.Payslip;
import com.ihr360.payroll.model.vo.PayrollConfigVo;
import com.ihr360.payroll.model.vo.SalaryFieldVo;
import com.ihr360.shared.entitywithlistener.NumberIdWithTimeAndCompanyId;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.Type;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import java.util.ArrayList;
import java.util.List;


/** 工资单配置，staff用 */
@NoArgsConstructor
@Data
@Entity
@Table(uniqueConstraints = @UniqueConstraint(columnNames = {"companyId", "name"}))
public class PayslipConfig extends NumberIdWithTimeAndCompanyId<Long> {
    /** 名称 */
    @Column(nullable = true, length = 50)
    private String name;

    /**
     * 是否启用
     */
    private boolean enabled = true;

    /** 工资单配置的字段是工资表的子集 */
    @ManyToMany
    private List<SalaryField> fields = new ArrayList<>();

    /**
     * blob，二进制形式的长文本数据,BLOB类型 最大65535=64k
     * 这里面放了行内的所有数据，数据通过序列化后存入
     * 表头信息,这个信息和fields中的信息有一定重合，可以认为是fields的精简信息定义
     */
    @Column(columnDefinition = "text")
    @Type(type = "json")
    private List<DynamicHeaderCell> header;

    private boolean defaultPayslipConfig = false;

    /**
     * 工资单
     */
    @OneToMany(mappedBy = "config", orphanRemoval = true, cascade = CascadeType.ALL)
    private List<Payslip> payslips = new ArrayList<>();

    public PayslipConfig(Long id) {
        super.id = id;
    }

    public List<SalaryFieldVo> getFieldVos() {
        List<SalaryFieldVo> salaryFieldVoList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(fields)) {
            fields.forEach(field -> {
                PayrollConfigVo payrollConfig = null;
                if (field.getConfig() != null) {
                    PayrollConfig config = field.getConfig();
                    payrollConfig = new PayrollConfigVo(config.getId(), config.getName(), new ArrayList<>(),config.getSalaryAdjustFormula());
                }
                salaryFieldVoList.add(new SalaryFieldVo(field.getId(), field.getCode(), payrollConfig, field.getMeta(), field.getSource(),
                        field.getValueMeta(), field.getName(), field.getType(), field.getTaxType(), field.isTaxMergeField(), field.getPersonalSalaryNumOp(),
                        field.getCompanyCostNumOp()));
            });
        }
        return salaryFieldVoList;
    }


}